package com.mayikt;

/**
 * @Author: maplefire
 * @Description: 证明同步方法使用this锁
 * @Date: 2022/06/17 14:26
 */
class ThreadDemo02 implements Runnable {

    private int count = 100;
    private Object obj = new Object();
    public volatile Boolean flag = true;

    public void run() {
        if (flag) {
            while (count > 0) {
                try {
                    Thread.sleep(10);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                // 换成this，线程安全
                synchronized (obj) {
                    if (count > 0) {
                        System.out.println(Thread.currentThread().getName() + ",出售第" + (100 - count + 1) + "张票");
                        count--;
                    }
                }
            }
        }

        while (count > 0) {
            try {
                Thread.sleep(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            sale();
        }
    }

    public synchronized void sale() {
        if (count > 0) {
            System.out.println(Thread.currentThread().getName() + ",出售第" + (100 - count + 1) + "张票");
            count--;
        }
    }
}

public class Test02 {
    public static void main(String[] args) throws InterruptedException {
        ThreadDemo02 threadDemo02 = new ThreadDemo02();
        Thread t1 = new Thread(threadDemo02, "窗口1");
        Thread t2 = new Thread(threadDemo02, "窗口2");
        t1.start();
        Thread.sleep(40);
        threadDemo02.flag = false;
        t2.start();
    }
}
